<template>
  <span ref="imgInstance">
    <nuxt-img
      :src="imgUrl"
      v-if="imgUrl"
      :class="
        $cn(
          props.class,
          'duration-700  ease-in-out w-full h-full cursor-pointer object-contain',
          isLoading ? 'scale-105 blur-lg' : 'scale-100 blur-0'
        )
      "
      loading="lazy"
      :alt="alt"
      :title="alt"
      @error="imgError"
      @load="imgLoaded"
    />
  </span>
</template>
<script setup lang="ts">
// https://image.nuxt.com/usage/nuxt-img#events
import { useIntersectionObserver } from "@vueuse/core";
import { ref, useTemplateRef } from "vue";
const isLoading = ref(true);
const props = defineProps({
  class: {
    type: String,
    default: "",
  },
  alt: {
    type: String,
    default: "",
  },
  src: {
    type: String,
    required: true,
  },
});
const imgInstance = useTemplateRef<HTMLElement>("imgInstance");
const imgError = () => {
  imgUrl.value = "/image/404.jpg";
  isLoading.value = false;
};
const imgUrl = ref("");

const imgLoaded = () => {
  isLoading.value = false;
  // const el = imgInstance.value.$el as HTMLImageElement;
  // console.log("宽度", el.);
  // fetch(props.src)
  //   .then((res) => {
  //     console.log(res);
  //   })
  //   .catch((err) => {
  //     imgUrl.value = "/image/404.jpg";
  //     console.log("获取图片失败");
  //   });
};
let ObInstance: any = null;
onMounted(() => {
  if (window && window.IntersectionObserver) {
    const { stop } = useIntersectionObserver(imgInstance, ([entry], observerElement) => {
      // targetIsVisible.value = entry?.isIntersecting || false
      if (entry.isIntersecting) {
        imgUrl.value = props.src;
      }
    });
    ObInstance = stop;
  } else {
    imgUrl.value = props.src;
  }
  // console.log(imgInstance.value);
  // console.log(imgInstance.value.$el);
  // const el = imgInstance.value.$el as HTMLImageElement;
  // console.log("宽度", el.);
});
onUnmounted(() => {
  if (ObInstance) {
    ObInstance();
  }
});
</script>
<style lang="scss" scoped>
.blur_img {
}
</style>
